package com.libo.client.gather.impl;

import com.libo.bean.Environment;
import com.libo.client.gather.Gather;
import com.libo.utils.BeanCopyUtils;
import com.libo.utils.DateTimeUtils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GatherImpl implements Gather {

    private List<Environment> environments = new ArrayList<>();

    @Override
    public List<Environment> gather() {
        //声明缓冲字符输入流
        BufferedReader br = null;
        try {
            //创建缓冲字符输入流
            br = new BufferedReader(new FileReader("D:\\code\\idea_code\\Smart\\src\\main\\resources\\data-file-simple"));

            String temp;
            while ((temp = br.readLine()) != null){
                //数据处理
                dataHandler(temp);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return environments;
    }

    /**
     * 解析数据
     * @param temp 100|101|2|16|1|3|57a491fc02|1|1516413763738
     */
    private void dataHandler(String temp) {
        //分割字符串
        String[] split = temp.split("[|]");
        //对环境数据进行初始化
        Environment environment = new Environment().setSendId(split[0])
                .setSmartId(split[1])
                .setAreaModelId(split[2])
                .setSensorAddress(split[3])
                .setSensorCount(Integer.parseInt(split[4]))
                .setInstructionDesignation(split[5])
                .setStatus(Integer.parseInt(split[7]))
                .setGatherTime(DateTimeUtils.timeCoverLocalDateTime(Long.parseLong(split[8])));

        if ("16".equals(split[3])){
            // 温度湿度
            Environment humidity = BeanCopyUtils.copy(environment);
            environment.setName("温度")
                    .setEnvironmentData(((Float.parseFloat(Integer.valueOf(split[6].substring(0, 4), 16).toString()))*(0.00268127F))-46.85F);
            humidity.setName("湿度")
                    .setEnvironmentData(((Float.parseFloat(Integer.valueOf(split[6].substring(4, 8), 16).toString()))*0.00190735F)-6);

            environments.add(humidity);
        } else if ("256".equals(split[3])) {
            //光照强度
            environment.setEnvironmentData(Float.parseFloat(Integer.valueOf(split[6].substring(0, 4), 16).toString()))
                    .setName("光照强度");
        }else{
            // 二氧化碳浓度
            environment.setEnvironmentData(Float.parseFloat(Integer.valueOf(split[6].substring(0, 4), 16).toString()))
                    .setName("二氧化碳浓度");
        }

        environments.add(environment);
    }
}